<?php 
namespace app\admin\model;
use think\Model;
use think\Db;
use think\Log;

class Tasks extends Model
{
    public function task_handle($if_on,$task)
    {
        $result = array('err'=>'1','content'=>'','if_on'=>'');
        $log = [
        		'time' => date('Y-m-d H:i:s',time()),
        ];
        $exc_log = db('tasks')->where('task',$task)->value('exc_log');
        $exc_log = json_decode($exc_log,true);
        if ($if_on == '0'){
        	$log['message'] = "关闭任务";
        }elseif ($if_on == '1'){
        	$log['message'] = "开启任务";
        }
        array_push($exc_log, $log);
        $exc_log = json_encode($exc_log,JSON_UNESCAPED_UNICODE);
        $save_info = db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$exc_log]);
        if ($save_info == false){
            $result['if_on'] = ($if_on == '1') ? '0' : '1';
            $result['content'] = '更新失败！';
            $result = json_encode($result);
            return $result;
        }
        $result['err'] = '0';
        $result['content'] = '更新成功！';
        $result['if_on'] = $if_on;
        $result = json_encode($result);
        return  $result;
    }
    
    private function if_match_time($exc_time)
    {
    	
        $result = false;
        if (preg_match('/^00-00 [0-2][0-9]\:[0-6][0-9]$/',$exc_time)){
            $result = (date('H:i',time())==preg_replace('/^00-00 /','',$exc_time)) ? true:false;
        }elseif (preg_match('/^00-([0-2][0-9]|3[0-1]) [0-2][0-9]\:[0-6][0-9]$/', $exc_time)){
        	$result = (date('d H:i',time())==preg_replace('/^00-/', '', $exc_time)) ? true:false;
        }elseif (preg_match('/^(0[1-9]|1[1-2])-([1-2][1-9]|3[0-1]) [0-2][0-9]\:[0-6][0-9]$/',$exc_time)){
            $result = (date('m-d H:i',time()) == $exc_time) ? true : false;
        }
        return $result;
    }
    
    protected  function if_out_of_clearance_time($exc_time,$clearance_time)
    {
    	
    	$result = 0;
    	if (preg_match('/^00-00 [0-2][0-9]\:[0-6][0-9]$/',$exc_time)){
            $now= date('H:i',time());
            $exc_time = preg_replace('/^00-00 /','',$exc_time);
        }elseif (preg_match('/^00-([0-2][0-9]|3[0-1]) [0-2][0-9]\:[0-6][0-9]$/', $exc_time)){
        	$now = date('d H:i',time());
        	$exc_time = preg_replace('/^00-/', '', $exc_time);
        }elseif (preg_match('/^(0[1-9]|1[1-2])-([1-2][1-9]|3[0-1]) [0-2][0-9]\:[0-6][0-9]$/',$exc_time)){
            $now = date('m-d H:i',time());
        }
        $exc_time = strtotime($exc_time);
        $now = strtotime($now);
        $clearance = $exc_time - $now ;
        if ($clearance < 0){
        	$exc_time = $exc_time + 24*60*60;
        	$clearance = $exc_time- $now;
        }
        $result = abs($clearance) - abs($clearance_time) > 0 ? false : true;
        
//         file_put_contents(RUNTIME_PATH.'test'.DS.'time.txt', " /r".$clearance.' =>'.$clearance_time,FILE_APPEND);
        
      return $result;
    	
    }
    private function connection_log($connection_status)
    {
        switch ($connection_status)
        {
            case CONNECTION_NORMAL:
                $result = 'Connection is in a normal state';
                break;
            case CONNECTION_ABORTED:
                $result = 'Connection aborted';
                break;
            case CONNECTION_TIMEOUT:
                $result = 'Connection timed out';
                break;
            case (CONNECTION_ABORTED & CONNECTION_TIMEOUT):
                $result = 'Connection aborted and timed out';
                break;
            default:
                $result = 'Unknown';
                break;
        }
        return $result;
    }
    
	public function del_log($task)
	{
		ignore_user_abort(true);
    	set_time_limit(0);
    	session_write_close();
    	$if_on = db('tasks')->where('task',$task)->value('if_on');
    	while ($if_on == '1'){
			$task_info = db('tasks')->field(['task','if_on','time','exc_type','exc_time','exc_log'])->where('task',$task)->find();
    		$if_on = $task_info['if_on'];
    		if ($if_on == '0'){
    			break;
    		}
    	    $log_arr = $task_info['exc_log'];
    	    $log_arr = json_decode($log_arr,true);
    	    $log = array('time'=>date('Y-m-d H:i:s'),time(),'message' => '0');
    		if ($task_info['exc_type'] == '1'){
    		    $act_del_log = db('tasks')->where('id','<>','0')->update(['exc_log'=>json_encode(array())]);
    		    if (!$act_del_log){
    		    	$log['message'] = '删除日志失败';
    		    }else {
    		    	$log['message'] = '删除日志成功';
    		    }
    		}elseif ($task_info['exc_type'] == '2'){
    			$if_match_time = $this->if_match_time($task_info['exc_time']);
    			if ($if_match_time){
    			    $act_del_log = db('tasks')->where('id','<>','0')->update(['exc_log'=>json_encode(array())]);
    			    if (!$act_del_log){
    			    	$log['message'] = '删除日志失败';
    			    }else {
    			    	$log['message'] = '删除日志成功';
    			    }
    			}
    		}
    		if ($log['message'] != '0')
    		{
    			array_push($log_arr, $log);
    			$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
    			$insert_log = db('tasks')->where('task',$task)->update(['exc_log'=>$log_arr]);
    		}
    		
    		if (connection_aborted()){
    		    $log = array();
    		    $log['time'] = date('Y-m-d H:i:s',time());
    		    $log['message'] = $this->connection_log(connection_status());
    		    $log_arr = db('tasks')->where('task','task')->value('exc_log');
    		    $log_arr = json_decode($log_arr);
    		    array_push($log_arr, $log);
    		    $log_arr = json_encode($log_arr);
    		    $if_on = '1';
    		    $insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
    		    break;
    		}
    		if ($task_info['exc_type'] == '1'){
    			sleep(intval($task_info['time']));
    		}elseif ($task_info['exc_type'] == '2'){
    			$if_match_time = $this->if_match_time($task_info['exc_time']);
    			if ($if_match_time == false){
    				$if_out_time = $this->if_out_of_clearance_time($task_info['exc_time'], $task_info['time']);
    				if ($if_out_time){
    					continue;
    				}
    				sleep(intval($task_info['time']));
    			}else {
    				sleep(31);
    			}
    		}
    		
    	}
	}
	
	
	public function del_tmp_file($task)
	{
	    ignore_user_abort();
	    set_time_limit(0);
	    $tmp_dir = array(
	    		ROOT_PATH.'Uploads'.DS.'users'.DS,
	    		ROOT_PATH.'Uploads'.DS.'policy_temp'.DS
	    );
	    $if_on = db('tasks')->where('task',$task)->value('if_on');
	    while ($if_on == '1'){
	    	try {
	    		$task_info = db('tasks')->field(['task','if_on','time','exc_type','exc_time','exc_log'])->where('task',$task)->find();
	    		$log_arr = json_decode($task_info['exc_log'],true);
	    		$log = array('time' => date('Y-m-d H:i:s',time()),'message' => '0');
	    		$if_on = $task_info['if_on'];
	    		if ($if_on == '0'){
	    			break;
	    		}
	    		 
	    		
	    		if ($task_info['exc_type'] == '1'){
	    			$log['message'] = '';
	    			foreach ($tmp_dir as $tk => $tv){
	    				if (file_exists($tv)){
	    					$log['message'] = $this->del_dir($tv)? $log['message'] : $log['message'].$tv.'删除失败';
	    		
	    				}
	    			}
	    		}elseif ($task_info['exc_type'] == '2'){
	    			$if_match_time = $this->if_match_time($task_info['exc_time']);
	    			if ($if_match_time){
	    				$log['message'] = '';
	    				foreach ($tmp_dir as $tk => $tv){
	    					if (file_exists($tv)){
	    						$log['message'] .= $this->del_dir($tv)? $log['message'] : $tv.'删除失败';
	    					}
	    				}
	    			}
	    		}
	    		
	    		if ($log['message'] == ''){
	    			$log['message'] = '删除成功';
	    		}
	    		if ($log['message'] != '0'){
	    			array_push($log_arr, $log);
	    			$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
	    			$insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
	    		}
	    		
	    		if (connection_aborted()){
	    			$log = array();
	    			$log['time'] = date('Y-m-d H:i:s',time());
	    			$log['message'] = $this->connection_log(connection_status());
	    			$log_arr = db('tasks')->where('task','task')->value('exc_log');
	    			$log_arr = json_decode($log_arr);
	    			array_push($log_arr, $log);
	    			$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
	    			$if_on = '1';
	    			$insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
	    			break;
	    		}
	    		
	    		if ($task_info['exc_type'] == '1'){
	    			sleep(intval($task_info['time']));
	    		}elseif ($task_info['exc_type'] == '2'){
	    			$if_match_time = $this->if_match_time($task_info['exc_time']);
	    			if ($if_match_time == false){
	    		
	    				$if_out_time = $this->if_out_of_clearance_time($task_info['exc_time'], $task_info['time']);
	    		
	    				if ($if_out_time){
	    					continue;
	    				}
	    				sleep(intval($task_info['time']));
	    			}else {
	    				sleep(31);
	    			}
	    			//     			sleep(intval($task_info['time']));
	    		}
	    	}catch (\Exception $e){
	    		Log::write($e->getMessage(),'error');
	    	}
// 	        $task_info = db('tasks')->field(['task','if_on','time','exc_type','exc_time','exc_log'])->where('task',$task)->find();
// 	        $log_arr = json_decode($task_info['exc_log'],true);
// 	        $log = array('time' => date('Y-m-d H:i:s',time()),'message' => '0');
// 	        $if_on = $task_info['if_on'];
// 	        if ($if_on == '0'){
// 	        	break;
// 	        }
	        

// 	        if ($task_info['exc_type'] == '1'){
// 	        	$log['message'] = '';
// 	        	foreach ($tmp_dir as $tk => $tv){
// 	        		if (file_exists($tv)){
// 	        			$log['message'] = unlink($tk)? $log['message'] : $log['message'].$tv.'删除失败';
	        			
// 	        		}
// 	        	}
// 	        }elseif ($task_info['exc_type'] == '2'){
// 	            $if_match_time = $this->if_match_time($task_info['exc_time']);
// 	            if ($if_match_time){
// 	            	$log['message'] = '';
// 	            	foreach ($tmp_dir as $tk => $tv){
// 	            		if (file_exists($tv)){
// 	            			$log['message'] .= unlink($tk)? $log['message'] : $tv.'删除失败';
// 	            		}
// 	            	}
// 	            }
// 	        }
	        	    
// 	        if ($log['message'] == ''){
// 	        	$log['message'] = '删除成功';
// 	        }
// 	        if ($log['message'] != '0'){
// 	        	array_push($log_arr, $log);
// 	        	$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
// 	        	$insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
// 	        }
	       
// 	        if (connection_aborted()){
// 	            $log = array();
// 	            $log['time'] = date('Y-m-d H:i:s',time());
// 	            $log['message'] = $this->connection_log(connection_status());
// 	            $log_arr = db('tasks')->where('task','task')->value('exc_log');
// 	            $log_arr = json_decode($log_arr);
// 	            array_push($log_arr, $log);
// 	            $log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
// 	            $if_on = '1';
// 	            $insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
// 	            break;
// 	        }
	         
// 	    	if ($task_info['exc_type'] == '1'){
//     			sleep(intval($task_info['time']));
//     		}elseif ($task_info['exc_type'] == '2'){
//     			$if_match_time = $this->if_match_time($task_info['exc_time']);
//     			if ($if_match_time == false){
    				
//     				$if_out_time = $this->if_out_of_clearance_time($task_info['exc_time'], $task_info['time']);
    				
//     				if ($if_out_time){
//     					continue;
//     				}
//     				sleep(intval($task_info['time']));
//     			}else {
//     				sleep(31);
//     			}
// //     			sleep(intval($task_info['time']));
//     		}
	    }
	}
	
	public function db_backup($task)
	{
		ignore_user_abort(true);
		set_time_limit(0);
		session_write_close();
		$if_on = db('tasks')->where('task',$task)->value('if_on');
		while ($if_on == '1'){
			$task_info = db('tasks')->field(['task','if_on','time','exc_type','exc_time','exc_log'])->where('task',$task)->find();
			$if_on = $task_info['if_on'];
			if ($if_on == '0'){
				break;
			}
			$log_arr = $task_info['exc_log'];
			$log_arr = json_decode($log_arr,true);
			$log = array('time'=>date('Y-m-d H:i:s',time()),'message' => '0');
			if ($task_info['exc_type'] == '1'){
				$act_backup = $this->exportDatabase();
			    $log['message'] = $act_backup;
			}elseif ($task_info['exc_type'] == '2'){
				$if_match_time = $this->if_match_time($task_info['exc_time']);
				if ($if_match_time){
				    $act_backup = $this->exportDatabase();
				    $log['message'] = $act_backup;
				}
			}
			if ($log['message'] != '0'){
				array_push($log_arr, $log);
				$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
				$insert_log = db('tasks')->where('task',$task)->update(['exc_log'=>$log_arr]);
			}
			
			if (connection_aborted()){
			    $log = array();
			    $log['time'] = date('Y-m-d H:i:s',time());
			    $log['message'] = $this->connection_log(connection_status());
			    $log_arr = db('tasks')->where('task','task')->value('exc_log');
			    $log_arr = json_decode($log_arr);
			    array_push($log_arr, $log);
			    $log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
			    $if_on = '1';
			    $insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
			    break;
			}
			if ($task_info['exc_type'] == '1'){
    			sleep(intval($task_info['time']));
    		}elseif ($task_info['exc_type'] == '2'){
    			$if_match_time = $this->if_match_time($task_info['exc_time']);
    			if ($if_match_time == false){
    				$if_out_time = $this->if_out_of_clearance_time($task_info['exc_time'], $task_info['time']);
    				if ($if_out_time){
    					continue;
    				}
    				sleep(intval($task_info['time']));
    			}else {
    				sleep(31);
    			}
    		}
		}
	}
	
	public function del_tmp_data($task)
	{
		
		ignore_user_abort(true);
		set_time_limit(0);
		session_write_close();
		$if_on = db('tasks')->where('task',$task)->value('if_on');
		while ($if_on == '1'){
			$task_info = db('tasks')->field(['task','if_on','time','exc_type','exc_time','exc_log'])->where('task',$task)->find();
			$if_on = $task_info['if_on'];
			if ($if_on == '0'){
				break;
			}
			$log_arr = $task_info['exc_log'];
			$log_arr = json_decode($log_arr,true);
			$log = array('time'=>date('Y-m-d H:i:s'),time(),'message' => '0');
			
			$tmp_data_info = [
					array('db' => 'ousertmp','where' =>'if_agree > 0')
			];
			
			if ($task_info['exc_type'] == '1'){
				$act_del_tmp_data = true;
				foreach ($tmp_data_info as $tk => $tv){
					$act_del_tmp_data = db($tv['db'])->where($tv['where'])->delete();
					if ($act_del_tmp_data == false){
						break;
					}
				}
				if (!$act_del_tmp_data){
					$log['message'] = '删除临时数据失败';
				}else {
					$log['message'] = '删除数据成功';
				}
			}elseif ($task_info['exc_type'] == '2'){
				$if_match_time = $this->if_match_time($task_info['exc_time']);
				if ($if_match_time){
					$act_del_tmp_data = true;
					foreach ($tmp_data_info as $tk => $tv){
						$act_del_tmp_data = db($tv['db'])->where($tv['where'])->delete();
						if ($act_del_tmp_data == false){
							break;
						}
					}
					if (!$act_del_tmp_data){
						$log['message'] = '删除临时数据失败';
					}else {
						$log['message'] = '删除数据成功';
					}
				}
			}
			if ($log['message'] != '0')
			{
				array_push($log_arr, $log);
				$log_arr = json_encode($log_arr,JSON_UNESCAPED_UNICODE);
				$insert_log = db('tasks')->where('task',$task)->update(['exc_log'=>$log_arr]);
			}
		
			if (connection_aborted()){
				$log = array();
				$log['time'] = date('Y-m-d H:i:s',time());
				$log['message'] = $this->connection_log(connection_status());
				$log_arr = db('tasks')->where('task','task')->value('exc_log');
				$log_arr = json_decode($log_arr);
				array_push($log_arr, $log);
				$log_arr = json_encode($log_arr);
				$if_on = '1';
				$insert_log = @db('tasks')->where('task',$task)->update(['if_on'=>$if_on,'exc_log'=>$log_arr]);
				break;
			}
			if ($task_info['exc_type'] == '1'){
				sleep(intval($task_info['time']));
			}elseif ($task_info['exc_type'] == '2'){
				$if_match_time = $this->if_match_time($task_info['exc_time']);
				if ($if_match_time == false){
					$if_out_time = $this->if_out_of_clearance_time($task_info['exc_time'], $task_info['time']);
					if ($if_out_time){
						continue;
					}
					sleep(intval($task_info['time']));
				}else {
					sleep(31);
				}
			}
		
		}
	}
	
	public function save_task($task_info)
	{
	    $tasks = new Tasks;
	    if (isset($task_info['id'])){
	        $result = $tasks->save($task_info,['id'=>$task_info['id']]);
	        return $result;
	    }
	    $tasks->task = $task_info['task'];
	    $tasks->task_decr = $task_info['task_decr'];
	    $tasks->exc_type = $task_info['exc_type'];
	    $tasks->exc_time = $task_info['exc_time'];
	    $tasks->time = $task_info['time'];
	    $tasks->exc_log = json_encode(array());
	    $tasks->created = time();
	    $result = $tasks->save();
	    return $result;
	}
	
	
	private  function exportDatabase(){
		$result = '';
		$path = RUNTIME_PATH.'mysql/';
		$database = config('database')['database'];
		
		$info = "-- ----------------------------\r\n";
		$info .= "-- 日期：".date("Y-m-d H:i:s",time())."\r\n";
		$info .= "--  Database - ".$database."\r\n";
		$info .= "-- ----------------------------\r\n\r\n";
		$info .= "CREATE DATAbase IF NOT EXISTS `".$database."` DEFAULT CHARACTER SET utf8 ;\r\n\r\n";
		$info .= "USE `".$database."`;\r\n\r\n";
	
		// 检查目录是否存在
		if(is_dir($path)){
			// 检查目录是否可写
			if(is_writable($path)){
				//echo '目录可写';exit;
			}else{
				//echo '目录不可写';exit;
				chmod($path,0777);
			}
		}else{
			//echo '目录不存在';exit;
			// 新建目录
			mkdir($path, 0777, true);
			//chmod($path,0777);
		}
	
		// 检查文件是否存在
		$file_name = $path.$database.'-'.date("Y-m-d",time()).'.sql';
		if(file_exists($file_name)){
			$result = '备份目录已存在！';
			return $result;
		}
		file_put_contents($file_name,$info,FILE_APPEND);
	
		//查询数据库的所有表
		$result = Db::query('show tables');
		//print_r($result);exit;
		foreach ($result as $k=>$v) {
			//查询表结构
			$val = $v['Tables_in_'.$database];
			$sql_table = "show create table ".$val;
			$res = Db::query($sql_table);
			//print_r($res);exit;
			$info_table = "-- ----------------------------\r\n";
			$info_table .= "-- Table structure for `".$val."`\r\n";
			$info_table .= "-- ----------------------------\r\n\r\n";
			$info_table .= "DROP TABLE IF EXISTS `".$val."`;\r\n\r\n";
			$info_table .= $res[0]['Create Table'].";\r\n\r\n";
			//查询表数据
			$info_table .= "-- ----------------------------\r\n";
			$info_table .= "-- Data for the table `".$val."`\r\n";
			$info_table .= "-- ----------------------------\r\n\r\n";
			file_put_contents($file_name,$info_table,FILE_APPEND);
			$sql_data = "select * from ".$val;
			$data = Db::query($sql_data);
			//print_r($data);exit;
			$count= count($data);
			//print_r($count);exit;
			if($count<1) continue;
			foreach ($data as $key => $value){
				$sqlStr = "INSERT INTO `".$val."` VALUES (";
				foreach($value as $v_d){
					$v_d = str_replace("'","\'",$v_d);
					$sqlStr .= "'".$v_d."', ";
				}
				//需要特别注意对数据的单引号进行转义处理
				//去掉最后一个逗号和空格
				$sqlStr = substr($sqlStr,0,strlen($sqlStr)-2);
				$sqlStr .= ");\r\n";
				file_put_contents($file_name,$sqlStr,FILE_APPEND);
			}
			$info = "\r\n";
			file_put_contents($file_name,$info,FILE_APPEND);
		}
		
		$result = '数据备份完成！';
	}
	
	//删除文件夹
	public function del_dir($path)
	{
		if (is_dir($path)){
			$files = scandir($path);
			foreach ($files as $fk => $fv){
				if ($fv != '.' && $fv != '..'){
					if (is_dir($path.$fv)){
						$this->del_dir($path.$fv.DS);
						rmdir($path.$fv.DS);
					}else {
						unlink($path.$fv);
					}
				}
				
			}
		}
		return true;
	}
}